﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CookieLogin.Filters
{
    public class LoginFilter : Attribute, IAuthorizationFilter
    {
        private readonly ILogger<LoginFilter> _logger;
        private readonly IModelMetadataProvider _modelMetadataProvider;
        public LoginFilter(ILogger<LoginFilter> logger
            , IModelMetadataProvider modelMetadataProvider)
        {
            _modelMetadataProvider = modelMetadataProvider;
            _logger = logger;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool flag = context.HttpContext.Request.Cookies.TryGetValue("UserId", out string UserIdStr);

            if (flag == false)
            {

                var result = new ViewResult { ViewName = "~/Views/UserLogin/Login.cshtml" };
                context.Result = result;


                //context.HttpContext.Response.Redirect("/UserLogin/Login");
            }
            else
            {
                var result = new ViewResult { };
                result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                result.ViewData.Add("UserName", "Admin");
                context.Result = result;
            }



        }
    }
}
